#!/bin/bash
#
# Forcibly locks a user out of their machine with no way back in without
# access to the FileVault recovery key.
#
# Otherwise, prevent the machine from booting by renaming launchd to
# launchd_disabled.
#
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

PATH="/usr/bin:/bin:/sbin:/usr/local/bin"

CURRENT_FV_USERS=$(fdesetup list 2>&1 | cut -d ',' -f 1)

LOCK_USER_UNAME=fde_locked_user
LOCK_USER_PASSW=$(openssl rand -base64 32)
LOCK_USER_NAME="Machine Disabled"
LOCK_USER_HINT="Machine Disabled"
LOCK_USER_SHELL=/usr/bin/false
LOCK_USER_GROUP=20
LOCK_USER_IMAGE="/Library/User Pictures/jolly-roger.jpg"

function check_for_root() {
  if [[ $(id -u) -ne 0 ]]; then
    echo "Not invoked as root, exiting."
    exit 99
  fi
}

function check_for_filevault() {
  fdesetup status | grep -q On
}

function create_temp_user() {
  dscl . create /Users/${LOCK_USER_UNAME}
  dscl . passwd /Users/${LOCK_USER_UNAME} ${LOCK_USER_PASSW}
  dscl . create /Users/${LOCK_USER_UNAME} UserShell ${LOCK_USER_SHELL}
  dscl . create /Users/${LOCK_USER_UNAME} PrimaryGroupID ${LOCK_USER_GROUP}
  dscl . create /Users/${LOCK_USER_UNAME} RealName "${LOCK_USER_NAME}"
  dscl . create /Users/${LOCK_USER_UNAME} Picture "${LOCK_USER_IMAGE}"
  dscl . create /Users/${LOCK_USER_UNAME} Hint "${LOCK_USER_HINT}"
}

function add_user_to_filevault() {
  fdeadduser ${LOCK_USER_UNAME} ${LOCK_USER_PASSW}
}

function remove_old_filevault_users() {
  for USER in ${CURRENT_FV_USERS}; do
    fdesetup remove -user ${USER}
  done
}

function break_machine() {
  mv -f /sbin/launchd /sbin/launchd_disabled
}

function main() {
  check_for_root

  if check_for_filevault; then
    create_temp_user
    add_user_to_filevault
    remove_old_filevault_users
  else
    break_machine
  fi

  halt -q
}

main ${@:-}
